package com.liuxl.wqdc.service;

import com.liuxl.wqdc.entity.*;
import com.liuxl.wqdc.repository.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


@Service
public class ManagerService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    ExamRepository examRepository;
    @Autowired
    TwoLevelQuestionRepository twoLevelQuestionRepository;
    @Autowired
    OneLevelQuestionRepository oneLevelQuestionRepository;
    @Autowired
    RecordRepository recordRepository;
    @Autowired
    BatchInsertRepository batchInsertRepository;


    public Integer checkLogin(String username, String password) {
        User user = userRepository.findByUsernameAndPassword(username, password);
        if (user != null) {
            return 1;
        } else {
            return 0;
        }
    }

    public JSONArray dataAnalyze(Integer examId) {
        JSONArray resultArr = new JSONArray();
        DecimalFormat df = new DecimalFormat("0.00");
        //1级问题列表
        List<OneLevelQuestion> oneLevelQuestionList = oneLevelQuestionRepository.findByExamId(examId);
        //2级问题列表
        List<Integer> oneLevelQuestionIdList = new ArrayList<>();
        for (int i = 0; i < oneLevelQuestionList.size(); i++) {
            oneLevelQuestionIdList.add(oneLevelQuestionList.get(i).getId());
        }
        List<TwoLevelQuestion> twoLevelQuestionList = twoLevelQuestionRepository.findByOneLevelQuestionIdIn(oneLevelQuestionIdList);
        //3级问题列表
        List<Integer> twoLevelQuestionIdList = new ArrayList<>();
        for (int j = 0; j < twoLevelQuestionList.size(); j++) {
            twoLevelQuestionIdList.add(twoLevelQuestionList.get(j).getId());
        }
        List<Record> recordList = recordRepository.findByTwoLevelQuestionIdInAndIsDelete(twoLevelQuestionIdList, "0");

        //组装数据
        JSONArray jsonArray = new JSONArray();
        for (int p = 0; p < oneLevelQuestionList.size(); p++) {
            JSONObject jsonTmp = new JSONObject();
            JSONArray jsonArray1 = new JSONArray();
            for (int k = 0; k < twoLevelQuestionList.size(); k++) {
                TwoLevelQuestion twoLevelQuestion = twoLevelQuestionList.get(k);
                if (twoLevelQuestion.getOneLevelQuestionId() == oneLevelQuestionList.get(p).getId()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", twoLevelQuestion.getTitle());
                    int scoreSum1 = 0;
                    int scoreSum2 = 0;
                    int scoreSum3 = 0;
                    int[] score1Arr1 = {0, 0, 0, 0};
                    int[] score1Arr2 = {0, 0, 0, 0};
                    int[] score1Arr3 = {0, 0, 0, 0};
                    int peopleNum = 0;//作答人数
                    for (int m = 0; m < recordList.size(); m++) {
                        Record record = recordList.get(m);
                        if (record.getTwoLevelQuestionId() == twoLevelQuestion.getId()) {
                            peopleNum++;
                            if (record.getResult1().equals("A")) {
                                score1Arr1[0] += 1;
                                scoreSum1 += 5;
                            } else if (record.getResult1().equals("B")) {
                                score1Arr1[1] += 1;
                                scoreSum1 += 4;
                            } else if (record.getResult1().equals("C")) {
                                score1Arr1[2] += 1;
                                scoreSum1 += 3;
                            } else if (record.getResult1().equals("D")) {
                                score1Arr1[3] += 1;
                                scoreSum1 += 0;
                            }

                            if (record.getResult2().equals("A")) {
                                score1Arr2[0] += 1;
                                scoreSum2 += 5;
                            } else if (record.getResult2().equals("B")) {
                                score1Arr2[1] += 1;
                                scoreSum2 += 4;
                            } else if (record.getResult2().equals("C")) {
                                score1Arr2[2] += 1;
                                scoreSum2 += 3;
                            } else if (record.getResult2().equals("D")) {
                                score1Arr2[3] += 1;
                                scoreSum2 += 0;
                            }

                            if (record.getResult3().equals("A")) {
                                score1Arr3[0] += 1;
                                scoreSum3 += 5;
                            } else if (record.getResult3().equals("B")) {
                                score1Arr3[1] += 1;
                                scoreSum3 += 4;
                            } else if (record.getResult3().equals("C")) {
                                score1Arr3[2] += 1;
                                scoreSum3 += 3;
                            } else if (record.getResult3().equals("D")) {
                                score1Arr3[3] += 1;
                                scoreSum3 += 0;
                            }

                        }
                    }
                    if (scoreSum1 != 0) {
                        jsonObject.put("zwpgAverageScore", df.format((float) scoreSum1 / peopleNum));

                    } else {
                        jsonObject.put("zwpgAverageScore", 0);

                    }
                    if (scoreSum2 != 0) {
                        jsonObject.put("zyxAverageScore", df.format((float) scoreSum2 / peopleNum));

                    } else {
                        jsonObject.put("zyxAverageScore", 0);

                    }

                    if (scoreSum3 != 0) {
                        jsonObject.put("xypyAverageScore", df.format((float) scoreSum3 / peopleNum));

                    } else {
                        jsonObject.put("xypyAverageScore", 0);

                    }

                    jsonObject.put("zwpgPeopleNum", score1Arr1);
                    jsonObject.put("zyxPeopleNum", score1Arr2);
                    jsonObject.put("xypyPeopleNum", score1Arr3);
                    jsonArray1.add(jsonObject);
                }
            }
            jsonTmp.put("children", jsonArray1);
            jsonArray.add(jsonTmp);
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            for (int j = 0; j < jsonObject.getJSONArray("children").size(); j++) {
                JSONObject resultItem = (JSONObject) jsonObject.getJSONArray("children").get(j);
                resultItem.put("num", (i + 1) + "." + (j + 1));
                resultArr.add(resultItem);
            }
        }
        return resultArr;
    }

    //获取全部记录
    public JSONObject findAllRecordByExamId(Integer examId, Integer page, Integer pageSize) {
        List<OneLevelQuestion> oneLevelQuestionList = oneLevelQuestionRepository.findByExamId(examId);
        List<Integer> oneLevelQuestionIdList = new ArrayList<>();
        for (int i = 0, len = oneLevelQuestionList.size(); i < len; i++) {
            oneLevelQuestionIdList.add(oneLevelQuestionList.get(i).getId());
        }
        List<TwoLevelQuestion> twoLevelQuestionList = twoLevelQuestionRepository.findByOneLevelQuestionIdIn(oneLevelQuestionIdList);

        List<Integer> twoLevelQuestionIdList = new ArrayList<>();
        for (int i = 0, len = twoLevelQuestionList.size(); i < len; i++) {
            twoLevelQuestionIdList.add(twoLevelQuestionList.get(i).getId());
        }
        Pageable pageable = PageRequest.of(page - 1, pageSize * twoLevelQuestionIdList.size(), Sort.Direction.DESC, "id");
        Page<Record> recordPage = recordRepository.findRecordByTwoQuestionIdAndPage(twoLevelQuestionIdList, pageable);
        //拼接数据
        List<Record> recordList = recordPage.getContent();
        JSONArray resultDataList = new JSONArray();
        String wenquanId = "";
        for (int i = 0, len = recordList.size(); i < len; i++) {
            if (i == 0) {
                wenquanId = recordList.get(i).getWenquanId();
                resultDataList.add(recordList.get(i));
            } else {
                if (!recordList.get(i).getWenquanId().equals(wenquanId)) {
                    wenquanId = recordList.get(i).getWenquanId();
                    resultDataList.add(recordList.get(i));
                }
            }
        }
        JSONObject resultObject = new JSONObject();
        resultObject.put("content", resultDataList);
        resultObject.put("totalPage", recordPage.getTotalPages());
        return resultObject;
    }

    //删除记录
    public void deleteRecord(String wenquanId) {
        List<Record> recordList = recordRepository.findByWenquanId(wenquanId);
        batchInsertRepository.batchDeleteRecord(recordList);
    }

    public JSONObject findRecordByFinishYears(Integer examId, String finishYears, Integer page, Integer pageSize) {
        List<OneLevelQuestion> oneLevelQuestionList = oneLevelQuestionRepository.findByExamId(examId);
        List<Integer> oneLevelQuestionIdList = new ArrayList<>();
        for (int i = 0, len = oneLevelQuestionList.size(); i < len; i++) {
            oneLevelQuestionIdList.add(oneLevelQuestionList.get(i).getId());
        }
        List<TwoLevelQuestion> twoLevelQuestionList = twoLevelQuestionRepository.findByOneLevelQuestionIdIn(oneLevelQuestionIdList);

        List<Integer> twoLevelQuestionIdList = new ArrayList<>();
        for (int i = 0, len = twoLevelQuestionList.size(); i < len; i++) {
            twoLevelQuestionIdList.add(twoLevelQuestionList.get(i).getId());
        }

        Pageable pageable = PageRequest.of(page - 1, pageSize * twoLevelQuestionIdList.size(), Sort.Direction.DESC, "id");
        Page<Record> recordPage = recordRepository.findByFinishYearsAndTwoLevelQuestionIdInAndIsDelete(finishYears, twoLevelQuestionIdList,"0", pageable);
        List<Record> recordList = recordPage.getContent();
        JSONArray resultDataList = new JSONArray();

        String wenquanId = "";
        for (int i = 0, len = recordList.size(); i < len; i++) {
            if (i == 0) {
                wenquanId = recordList.get(i).getWenquanId();
                resultDataList.add(recordList.get(i));
            } else {
                if (!recordList.get(i).getWenquanId().equals(wenquanId)) {
                    wenquanId = recordList.get(i).getWenquanId();
                    resultDataList.add(recordList.get(i));
                }
            }
        }
        JSONObject resultObject = new JSONObject();
        resultObject.put("content", resultDataList);
        resultObject.put("totalPage", recordPage.getTotalPages());
        return resultObject;
    }

    public JSONObject findQuestionInfoByWenquanId(String wenquanId,Integer examId) {
        JSONArray resultArr = new JSONArray();
        Optional<Exam> exam = examRepository.findById(examId);
        List<OneLevelQuestion> oneLevelQuestionList = oneLevelQuestionRepository.findByExamId(examId);
        List<Integer> oneQuestionIdList = new ArrayList<>();
        for (OneLevelQuestion oneLevelQuestion : oneLevelQuestionList) {
            oneQuestionIdList.add(oneLevelQuestion.getId());
        }
        List<TwoLevelQuestion> twoLevelQuestionList = twoLevelQuestionRepository.findByOneLevelQuestionIdIn(oneQuestionIdList);
        List<Record> recordList = recordRepository.findByWenquanId(wenquanId);
        for (int i = 0; i < oneLevelQuestionList.size(); i++) {
            JSONObject oneLevelQuestionJson = JSONObject.fromObject(oneLevelQuestionList.get(i));
            JSONArray jsonArrayTmp = new JSONArray();
            for (int j = 0; j < twoLevelQuestionList.size(); j++) {
                TwoLevelQuestion twoLevelQuestion = twoLevelQuestionList.get(j);
                if (twoLevelQuestion.getOneLevelQuestionId() == oneLevelQuestionList.get(i).getId()) {
                    JSONObject towlevelQuestionJSON =JSONObject.fromObject(twoLevelQuestion);
                    for (int k = 0; k < recordList.size(); k++) {
                        Record record = recordList.get(k);
                        if (record.getTwoLevelQuestionId() == twoLevelQuestion.getId()) {
                            towlevelQuestionJSON.put("result1",record.getResult1());
                            towlevelQuestionJSON.put("result2",record.getResult2());
                            towlevelQuestionJSON.put("result3",record.getResult3());
                        }
                    }
                    jsonArrayTmp.add(towlevelQuestionJSON);
                }
            }
            oneLevelQuestionJson.put("children", jsonArrayTmp);
            resultArr.add(oneLevelQuestionJson);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", exam.get().getId());
        jsonObject.put("title", exam.get().getTitle());
        jsonObject.put("studentName", recordList.get(0).getStudentName());
        jsonObject.put("finishYears", recordList.get(0).getFinishYears());
        jsonObject.put("peopleKind", exam.get().getPeopleKind());
        jsonObject.put("tips", exam.get().getTips());
        jsonObject.put("question", resultArr);
        return jsonObject;
    }
}

